const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const autoprefixer = require('autoprefixer');
const path = require('path');
const pkg = require('./package.json');

const webpack = require('webpack');
const ENV = process.env.NODE_ENV || 'development';
const IS_SERVER_RENDER = process.env.SERVER_RENDER || false;

const VERSION = `v${pkg.version}`;
const SOURCE_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'build');
const CLIENT_DIR = path.join(OUTPUT_DIR, VERSION);
const IS_PROD = ENV === 'production';

const entry = {
    'index': ['./pages/index/index.js'],
    'news': ['./pages/news/news.js'],
    'news-detail': ['./pages/news-detail/news-detail.js'],
    'sc-search-result': ['./pages/sc-search-result/sc-search-result.js'],
}

const htmlPlugins = () => {
    return Object.entries(entry).map(([key, value]) => {
        return new HtmlWebpackPlugin({
            title: key,
            template: `./pages/${key}/${key}.pug`,
            filename: IS_SERVER_RENDER ? `./pages/${key}/${key}.pug` : `./${key}.html`,
            // filename: `./pages/${key}.html`,
            inject: true,
            chunks: ['vendors', 'common', key]
        })
    })
}
let config = {
    mode: ENV,
    target: 'web',
    context: SOURCE_DIR,
    entry: {
        common: ['./common/common.js'],
        ...entry
    },
    output: {
        path: CLIENT_DIR,
        publicPath: IS_PROD ? 'http://www.chehangjia.cn:9003/' : '/',
        filename: 'assets/lib/[name].[hash:8].js',
        libraryTarget: 'umd',
    },

    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all',
                },
            },
        },
    },
    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension.
        extensions: [".ts", ".tsx", ".js"],
        alias: {
            layuiSrc: 'layui-src/dist/layui.all.js',
            layui: 'lib/layui/layui',
        }
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env']
                },
                exclude: /node_modules/,
            },
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            // { test: /\.tsx?$/, exclude: /node_modules/, loader: "ts-loader" },
            // { test: /\.pug?$/, exclude: /node_modules/, loader: "pug-loader" },
            {
                test: /\.less?$/,
                exclude: /node_modules/,
                use: [
                    // IS_PROD ? MiniCssExtractPlugin.loader : {
                    //     loader: 'style-loader',
                    //     options: { singleton: true },
                    // },
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        // options: { minimize: true },
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [autoprefixer({ browsers: 'last 5 versions' })],
                            sourceMap: true,
                        },
                    },
                    {
                        loader: 'less-loader',
                        options: {
                            javascriptEnabled: true,
                        },
                    },
                ]
            },
            {
                test: /\.css?$/,
                // exclude: /node_modules/,
                use: [
                    IS_PROD ? MiniCssExtractPlugin.loader : {
                        loader: 'style-loader',
                        options: { singleton: true },
                    },
                    {
                        loader: 'css-loader',
                        // options: { minimize: true },
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [autoprefixer({ browsers: 'last 5 versions' })],
                            sourceMap: true,
                        },
                    },
                ]
            },
            {
                test: /\.(svg|woff2?|ttf|eot|jpe?g|png|gif)(\?.*)?$/i,
                use: IS_PROD ? {
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        publicPath: '../image/',
                        outputPath: 'assets/image/',
                    },
                } : {
                        loader: 'url-loader',
                    },
            }
        ]
    },
    plugins: [
        // new webpack.optimize.OccurrenceOrderPlugin(),
        // new webpack.HotModuleReplacementPlugin(),
        // new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            PRODUCTION: JSON.stringify(IS_PROD),
        }),
        new CopyWebpackPlugin([
            { from: 'renderServer/', to: 'renderServer/' },
            { from: 'utils/', to: 'utils/' },
            { from: 'lib/layui/lay', to: 'assets/lib/lay' },
            { from: 'lib/layui/css', to: 'assets/lib/css' },
            { from: 'pages/includes', to: 'pages/includes'},
            { from: 'image/static', to: 'assets/image/static' },
        ]),
        new MiniCssExtractPlugin({
            filename: 'assets/style/[name].css',
            chunkFilename: 'assets/style/[id].css',
        }),
        ...htmlPlugins(),
    ],
    devServer: {
        compress: true,
        publicPath: '/',
        contentBase: SOURCE_DIR,
        port: 9002,
        proxy: {
            '/chj': {
                target: 'http://www.chehangjia.cn:8080'
            }
        }
    }
};
// console.log(IS_SERVER_RENDER)
if (IS_SERVER_RENDER) {
    config.plugins.push(new HtmlWebpackPugPlugin())
} else {
    config.module.rules.push(
        { test: /\.pug?$/, exclude: /node_modules/, loader: "pug-loader" }
    )
}
module.exports = config
